package user_service

import (
	"errors"
	"myserver/app/jwt"
	"myserver/app/model"
	"myserver/app/types"
	modelrsa "myserver/pkg/rsa"
	"myserver/pkg/utils"
	"time"
)

type UserService struct {
	Id int
	U  *types.User
}

// 创建用户
func (c *UserService) CreateUser() error {
	u, err := model.FindUserByAccount([]string{c.U.Account}, []string{})
	if err != nil {
		return err
	}
	if len(u) != 0 {
		return errors.New("用户名重复")
	}
	l, err := model.FindUserByAccount([]string{}, []string{c.U.Phone})
	if err != nil {
		return err
	}
	if len(l) != 0 {
		return errors.New("手机号已注册")
	}
	pass, err := modelrsa.Decrypt(c.U.Password)
	if err != nil {
		return errors.New("密码解析失败")
	}
	c.U.Password = pass
	c.U.Uuid = utils.GetUuid()
	return model.AddUser(c.U)
}

// 更新用户信息

func (UserService) UpDataUser(users []types.User) error {
	var (
		uuids []string
	)
	l := len(users)
	if l == 0 {
		return errors.New("请传入用户")
	}
	for i := 0; i < l; i++ {
		uuids = append(uuids, users[i].Uuid)
	}
	datas, err := model.FindUserByUuid(uuids)
	if err != nil {
		return err
	}
	for i := 0; i < len(datas); i++ {
		for j := 0; j < len(users); j++ {
			if datas[i].Uuid == users[j].Uuid {
				datas[i].NickName = users[j].NickName
				datas[i].Phone = users[j].Phone
				datas[i].Sex = users[j].Sex
				datas[i].Address = users[j].Address
				datas[i].Shops = users[j].Shops
				if users[j].Password != "" {
					pass, err := modelrsa.Decrypt(users[j].Password)
					if err != nil {
						return errors.New("密码解析失败")
					}
					if datas[i].Password == pass {
						return errors.New("用户NickName: " + datas[i].NickName + "密码不能和更改前的一致")
					}
					datas[i].Password = pass
				}
			}
		}

	}
	err = model.UpDataUser(&datas)
	if err != nil {
		return err
	}
	return nil
}

// 查询用户 uuid
func (UserService) FindUserByUuid(strs []string) ([]types.User, error) {
	users, err := model.FindUserByUuid(strs)
	return users, err
}

// 登陆
func (UserService) Login(Account string, passWord string) (string, error) {
	var (
		strs  []string
		token string
	)
	strs = append(strs, Account)
	users, err := model.FindUserByAccount(strs, []string{})
	if err != nil {
		return token, err
	}
	if len(users) == 0 {
		err = errors.New("未查询到此用户")
		return token, err
	}
	user := users[0]
	p, err := modelrsa.Decrypt(passWord)
	if err != nil {
		return token, errors.New("密码解析失败")
	}
	if user.Account != Account || user.Password != p {
		err = errors.New("用户名或密码不正确")
		return token, err
	}
	// time.Hour*24*100
	token, err = jwt.GetToken(user, time.Second*60*60)
	return token, err
}

// 删除用户
func (UserService) DellDatasByuuid(list []types.User) error {
	for i := 0; i < len(list); i++ {
		list[i].IsDel = 1
		list[i].DeleTime = time.Now()
	}
	return model.UpDataUser(&list)
}
func (UserService) GetUserInfo(token string) (*jwt.JwtUser, error) {
	return jwt.GetUserInfo(token)
}
func (UserService) GetUserList(page int, size int, key string) ([]types.User, int64, error) {
	return model.GETList[types.User](page, size, "account", key)
}
